<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>15 getSnapshotBeforeUpdate案例</title>
</head>

<style>
    .list {
        height: 200px;
        overflow: auto;
        border: 1px solid red;
    }
</style>

<body>
    <div id="root"></div>
</body>

<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/prop-types@15.8.1/prop-types.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<script type="text/babel">
    class App extends React.Component {
        constructor(props) {
            super(props)

            this.state = { newArr: [] }
        }

        listRef = React.createRef()

        componentDidMount() {
            this.timer = setInterval(() => {
                const { newArr } = this.state
                const news = `新闻${newArr.length + 1}`
                this.setState({ newArr: [news, ...newArr] })
            }, 100)
        }

        getSnapshotBeforeUpdate() {
            console.log('getSnapshotBeforeUpdate')
            
            return this.listRef.current.scrollHeight
        }

        componentDidUpdate(prevProps, prevState, height) {
            return this.listRef.current.scrollTop += this.listRef.current.scrollHeight - height
        }

        render() {
            const { newArr } = this.state

            return (
                <div className="list" ref={this.listRef}>
                    <ul>
                        {newArr.map((item, index) => (
                            <li key={index}>{item}</li>
                        ))}
                    </ul>
                </div>
            )
        }
    }

    const root = ReactDOM.createRoot(document.getElementById('root'))
    root.render(<App />)
</script>

</html>